
var proDictTable;
var isSubmit;
$(function () {

    //数据列表数据
	proDictTable = $('#proDictTable').DataTable({
		"bProcessing": false,
		"bLengthChange":true,
		"bServerSide": true,
		"bFilter": false,
		"bSort": false,
		"bStateSave":true,
		"pagingType":"full_numbers",
		"sAjaxSource": "../proDict/queryProDicts",
        "fnServerParams" : function(aDataSet) {
		   aDataSet.push(
				   {"name" : "dictCode","value" : $("#proDictSearchDiv #dictCode").val()}
				   )
		   },
	    "fbServerData":function(sSource,aDataSet){
		   $.ajax(
				   {"dataType":"json",
					   "type":"GET",
					   "url":sSource,
					   "data":aDataSet}
				   );
		   },
	    "aoColumns":[
	                {"mDataProp":"dictType"},
	                {"mDataProp":"dictCode"},
	                {"mDataProp":"dictKey"},
	                {"mDataProp":"dictVal"},
	                {"mDataProp":"dictExt5"},
	                {"mDataProp":"dictIndex"},
	                {"mDataProp":"dictId"}],	
	    "aoColumnDefs": [{ 
	 			"aTargets":[6],
	 			"mRender":function(data,type,full){
	 				var editBtn =  "<button class='btn btn-lightblue  btn-outline m-wrap' style='line-height:10px;font-size:10px;' data-json='"+JSON.stringify(full)+"' id='uptBtn'><i class=' icon-pencil'></i></button>";
	 				var delteBtn = "<button class='btn btn-lightpink btn-outline m-wrap' style='line-height:10px;font-size:10px;'  data-isroot='"+full.dictIsroot+"'  data-id='"+full.dictId+"' data-name='"+full.dictType+"' data-code='"+full.dictCode+"' id='dltBtn'><i class='icon-remove'></i></button>";
	 				var statusBtn = "<button class='btn btn-status btn-outline m-wrap' style='line-height:10px;font-size:10px;'  data-isroot='"+full.dictIsroot+"'  data-id='"+full.dictId+"' data-ext5='"+full.dictExt5+"' data-name='"+full.dictType+"' data-code='"+full.dictCode+"' id='statusBtn'><i class='icon-refresh'></i></button>";
	 				var statusBtn02 = "<button class='btn btn-status02 btn-outline m-wrap' style='line-height:10px;font-size:10px;'  data-isroot='"+full.dictIsroot+"'  data-id='"+full.dictId+"' data-ext5='"+full.dictExt5+"' data-name='"+full.dictType+"' data-code='"+full.dictCode+"' id='statusBtn'><i class='icon-refresh'></i></button>";
	 				if(full.dictVal && full.dictVal != ""){
	 					if(full.dictExt5=='1'){//按钮为禁用
	 						return editBtn + "&nbsp;&nbsp;&nbsp;" + delteBtn+"&nbsp;&nbsp;&nbsp;"+statusBtn;
	 					}else if(full.dictExt5=='2'){//按钮为启用
	 						return editBtn + "&nbsp;&nbsp;&nbsp;" + delteBtn+"&nbsp;&nbsp;&nbsp;"+statusBtn02;
	 					}
	 				}else{
	 					return delteBtn;
	 				}
	            }},{
	            	"aTargets":[4],
		 			"mRender":function(data,type,full){
		 				if(full.dictExt5=='1'){
		 					return "启用";
		 				}else if(full.dictExt5=='2'){
		 					return "禁用";
		 				}
		            }	
	            }],
	    "oLanguage":{"sUrl": "../resources/assets/plugins/dataTables/txt/page.txt"},
        "initComplete":function () {
            $('#proDictTable_length').find('select').selectpicker('render');
            $('#proDictTable_length').find('select').selectpicker('refresh');
            $('#proDictTable_length').find('.btn-group').css('width','auto');
            $('#proDictTable_length').find('.btn').css('background-color','#fff');
            $('#proDictTable_length').find('.btn').css('border','#d8d8d8 solid 1px')
        }
     });
	
	 dictTypeSelect();
	 
	 $('#proDictTable tbody').on('click','#statusBtn',function(){
		 var dictId = $(this).attr("data-id");
		 var dictExt5 = $(this).attr("data-ext5");
		 var dictCode = $(this).attr("data-code");
		 $.post('../proDict/updateExt5',{"id":dictId,"ext5":dictExt5,"dictCode":dictCode},function(data){
			 if(data){
				 var l = getValue();
				 swal("成功!","操作成功！", "success");
//				 reloadDictData();
				 if(l==0){
					 proDictTable.page(0).draw( 'page' );
				 }else{
					 var k = l/10;
					 proDictTable.page(k).draw( 'page' ); 
				 }
			 }else{
				 swal("失败!","操作失败！", "error");
			 }
		 });
	 });
	 
	 //填充控件后增加change方法
	 function initChangeDictCode(){
		$("#addProDictValueFrom #dictCode").change(function(){
			var dictType = $(this).find("option:selected").text();
			$("#addProDictValueFrom #dictType").val(dictType);
		});
	 }
	 
	//初始化表单验证,增加或删除
	function initProDictValueFrom(param){
		 isSubmit = false;
		 var url = "";
		 if(param == "add"){
			 url = "../proDict/addDictType";
		 }else if(param = "update"){
			 url = "../proDict/updateDictType";
		 }
		 $("#addProDictValueFrom").validate({
			  errorElement: 'span',
			  errorClass:'help-block help-block-error',
			  focusInvalid: false,ignore: '',
			  rules: {
				  dictType:{required: true},
				  dictKey:{required: true},
				  dictCode:{required: true},
				  dictVal:{required: true,remote:{type:'post',url:'../proDict/dictValVaild',data: {param:function(){return $("#addProDictValueDiv #dictVal").val()+","+$("#addProDictValueDiv #dictCode").val()+","+$("#addProDictValueDiv #dictId").val();;},dataType: "json",dataFilter:function (data){return data;}}}},
				  dictIndex:{required: true,dictIndexCheck:true}
			  },
			  messages:{dictVal:{remote:'该数据键值在此类型下已存在！'}},
			  errorPlacement: function(error,element){error.insertAfter(element);},
			  highlight: function(element) {$(element).closest('.control-group').addClass('error');},
			  unhighlight: function(element) {$(element).closest('.control-group').removeClass('error');},
			  success: function(label) {label.closest('.control-group').removeClass('error');},
			  submitHandler:function(form){
				 if(!isSubmit){
					 isSubmit = true;
					 $.post(url,$("#addProDictValueFrom").serialize(),function(data){
			    		if(data.flg) {	
			    			 swal("成功!","操作成功!", "success");
			    			 $("#addProDictValueDiv").modal("hide");
			    			 reloadDictData();isSubmit = false;
			    	    } else swal("失败!",data.errorMsg, "error");
			    	}); 
				 }
			     return false;
			  }
		 });
	 }
	 
	//添加数据键值按钮点击事件
	 $("#saveProDictValue").click(function(){
		var dictCode = $("#proDictSearchDiv #dictCode").val()+"";
		$("#addProDictValueDiv .modal-body").html(addProDictValue());
		initChangeDictCode();
		getDictCodeRefresh(dictCode);
		$("#addProDictValueDiv #divTitle").text("添加项目字典键值");
		initProDictValueFrom("add");
		$("#addProDictValueDiv").modal("show");
		
	});	
	
	//修改按钮
	$('#proDictTable tbody').on('click','#uptBtn',function(){
		var dictData = JSON.parse($(this).attr("data-json"));
		 $("#addProDictValueDiv .modal-body").html(addProDictValue(dictData));
		 $("#addProDictValueDiv #divTitle").text("修改项目字典键值");
		 initProDictValueFrom("update");
		 $("#addProDictValueDiv").modal("show");
	});
	
	//添加数据类型
	$("#saveProDict").click(function(){
		isSubmit = false;
		 $("#addProDictDiv .modal-body").html(addProDictDiv());
      	 $("#addProDictDiv").modal("show");
    	 $("#addProDictFrom").validate({
    			  errorElement: 'span',
    			  errorClass:'help-block help-block-error',
    			  focusInvalid: false,ignore: '',
    			  rules: {
    				  dictType: {required: true,remote:{type:'post',url:'../proDict/dictTypeVaild',data: {dictType:function(){return $("#addProDictDiv #dictType").val();}},dataType: "json",dataFilter:function (data){return data;}}},
    				  dictCode: {required: true,remote:{type:'post',url:'../proDict/dictCodeVaild',data: {dictType:function(){return $("#addProDictDiv #dictCode").val();}},dataType: "json",dataFilter:function (data){return data;}}}
    			  },
    			  messages:{	
    				  dictType:{remote:'该数据类型已存在！'},
    				  dictCode:{remote:'该数据编码已存在！'}
    			  },
    			  errorPlacement: function(error,element){error.insertAfter(element);},
    			  highlight: function(element) {$(element).closest('.control-group').addClass('error');},
    			  unhighlight: function(element) {$(element).closest('.control-group').removeClass('error');},
    			  success: function(label) {label.closest('.control-group').removeClass('error');},	
    			  submitHandler:function(form){
    				  if(!isSubmit){
    	   				 isSubmit = true;
    	   				 $.post("../proDict/addDictType",$("#addProDictFrom").serialize(),function(data){
     			    		if(data.flg) {
     			    			 swal("成功!","数据类型添加成功!", "success");
     			    			 $("#addProDictDiv").modal("hide");
     			    			 dictTypeSelect();
     			    			 reloadDictData();
     			    	    } else swal("失败!",data.errorMsg, "error");
	     			    }); 
    	   			  }
    			      return false;
    			  }
    		});
    	 
	});
	
	//提交按钮
	$("#addProDictBtn").click(function(){
   		$("#addProDictFrom").submit();
   	});
	$("#addProDictValueBtn").click(function(){
   		$("#addProDictValueFrom").submit();
   	});
   	//删除数据
	$('#proDictTable tbody').on('click','#dltBtn',function(){
		var id =JSON.parse($(this).attr("data-id"));
		var dictCode =$(this).attr("data-code");
		var dictName =$(this).attr("data-name");
		var dictIsroot = $(this).attr("data-isroot");
		var str = "";
		if(dictIsroot == 1){
			str="注意,当前为根节点，你确定删除该节点下全部数据吗?";
		}else{
			str = "您确定要删除"+dictName+"吗 ?";
		}
		confirm(str,function(isConfirm){
			if (isConfirm) {
				$.post("../proDict/deleDict",{id:id,dictIsroot:dictIsroot,dictCode:dictCode},function(data){
					if(data.flg){
						reloadDictData();
						dictTypeSelect();
						swal("", "当前操作成功 :)", "success");
					}else{
						swal("失败", data.errorMsg, "error");
					}
				});
			}else {
				swal("取消", "您的操作已经取消 :)", "error");
			}
		});
	});

	$.validator.addMethod("dictIndexCheck",function(value,element){
		return checkShuZi($("#addProDictValueFrom #dictIndex").val());
    },"<font color='#E47068'>请输入长度为8以内的数字</font>");
	
	function checkShuZi(val){
		var reg = /^[0-9]{0,8}$/i;
		if(reg.test(val)){
			return true;
		}       
		return false;
	}
});
//查询数据类型-下拉框
function dictTypeSelect(){
	$.post("../proDict/queryAllDictType",function(data){
		$("#proDictSearchDiv #dictCode").html("");
		if(data != null && typeof(data) != "undefined"){
			var str = "<option value=''></option>";
			for(var i = 0; i < data.length; i++){
				var dict = data[i];
				str = str + "<option value='"+ dict.dictCode +"'>"+dict.dictType+"</option>"
			}
			$("#proDictSearchDiv #dictCode").append(str);
        };
        $("#proDictSearchDiv #dictCode").selectpicker('render');
    	$("#proDictSearchDiv #dictCode").selectpicker('refresh');
   });
}

//拼接字符串
function getDictCodeRefresh(dictCode){
	$.post("../proDict/queryAllDictType",function(data){
		$("#addProDictValueDiv #dictType").html("");
		if(data != null && typeof(data) != "undefined"){
			var str = "<option value=''></option>";
			for(var i = 0; i < data.length; i++){
				var dict = data[i];
				str = str + "<option value='"+ dict.dictCode +"'>"+dict.dictType+"</option>"
			}
			$("#addProDictValueDiv #dictCode").html(str);
        };
        $('#addProDictValueDiv #dictCode').selectpicker('render');
        $('#addProDictValueDiv #dictCode').selectpicker('refresh');
        $('#addProDictValueDiv #dictCode').selectpicker('val',dictCode);
        var dictType = $("#addProDictValueDiv #dictCode").find("option:selected").text();
		$("#addProDictValueDiv #dictType").val(dictType);
 	});
	
}


//重新加载字典数据
function reloadDictData() {
	proDictTable.ajax.reload();
}

function getValue() {
	var oTable = $('#proDictTable').dataTable();
	var oSettings = oTable.fnSettings();
    return oSettings._iDisplayStart;
}